/**************************************************************************
 * @file usr_compare.c
 * @author 黑马小乌龟 (532352406@qq.com)
 * @brief
 * @version 0.1
 * @date 2025-10-17
 *
 * @copyright Copyright (c) 2025
 *
 *************************************************************************/
#include "hc32_ll_cmp.h"
#include "usr_compare.h"

static void CmpConfig(void);
static void DacConfig(void);

/**
 * @brief  Main function of cmp_normal_int project
 * @param  None
 * @retval int32_t return value, if needed
 */
int32_t usr_compare_init(void) {
    /* Configure DAC1 */
    DacConfig();
    /* Configure CMP */
    CmpConfig();
    /*NVIC configuration for interrupt */
    NVIC_EnableIRQ(CMP1_IRQ_IRQn);
    /* Peripheral registers write protected */

    return 0;
}

/**
 * @brief  DAC voltage configuration
 * @param  None
 * @retval None
 */
static void DacConfig(void) {
    stc_dac_init_t stcDacInit;
    uint16_t tmp;
    FCG_Fcg3PeriphClockCmd(DAC_PERIP_CLK, ENABLE);

    /* Init DAC by default value: source from data register and output enabled*/
    DAC_DeInit(DAC_TEST_UNIT);
    (void)DAC_StructInit(&stcDacInit);
    stcDacInit.u16Align = DAC_DATA_ALIGN;
    (void)DAC_Init(DAC_TEST_UNIT, DAC_CH, &stcDacInit);

    tmp = DEFAULT_OCP_DAC_VALUE;
    // tmp = DAC_VOL_0P2V;
    DDL_Printf("OCP DAC VALUE:%d\n",tmp);

    DAC_SetChData(DAC_TEST_UNIT, DAC_CH, tmp);
    (void)DAC_Start(DAC_TEST_UNIT, DAC_CH);
}

/**
 * @brief  Configure CMP.
 * @param  None
 * @retval None
 */
static void CmpConfig(void) {
    stc_cmp_init_t stcCmpInit;
    stc_gpio_init_t stcGpioInit;

    /* Enable peripheral Clock */
    FCG_Fcg3PeriphClockCmd(CMP_PERIP_CLK, ENABLE);

    /* Port function configuration for CMP */
    (void)GPIO_StructInit(&stcGpioInit);
    stcGpioInit.u16PinAttr = PIN_ATTR_ANALOG;
    (void)GPIO_Init(CMP1_INP1_PORT, CMP1_INP1_PIN, &stcGpioInit);
    // GPIO_SetFunc(CMP1_OUT_PORT, CMP1_OUT_PIN, CMP1_OUT_FUNC);

    /* Clear structure */
    (void)CMP_StructInit(&stcCmpInit);
    stcCmpInit.u16PositiveInput = (uint16_t)CMP_POSITIVE_INP2; /* PA3 */
    stcCmpInit.u16NegativeInput = (uint16_t)CMP_NEGATIVE_INM3; /* DA1O1 voltage */
    stcCmpInit.u16OutPolarity = CMP_OUT_INVT_OFF;
    stcCmpInit.u16OutDetectEdge = CMP_DETECT_EDGS_BOTH;
    stcCmpInit.u16OutFilter = CMP_OUT_FILTER_CLK_DIV32;
    stcCmpInit.u16HystVoltage = CMP_HYST_VOLT_10MV;
    (void)CMP_NormalModeInit(CMP_TEST_UNIT, &stcCmpInit);

    /* Enable interrupt if need */
    CMP_IntCmd(CMP_TEST_UNIT, ENABLE);
    /* Enable CMP output */
    CMP_CompareOutCmd(CMP_TEST_UNIT, ENABLE);
    /* Enable VCOUT */
    // CMP_PinVcoutCmd(CMP_TEST_UNIT, ENABLE);
}
